import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Button, Input, Modal } from '@/components';
import { message as Message, Tag, Pagination } from 'antd';
import axios from 'axios';
import PermissionTable, { PermissionRecord } from './components/PermissionTable';
import { useTranslation } from '@/utils/i18n'
import { useThemeStore } from '@/stores/themeStore'
// 权限管理组件 - 适配MongoDB数据显示
const PermissionManage: React.FC = () => {
  // 状态管理
  const [permissions, setPermissions] = useState<PermissionRecord[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  
  // 表单状态管理
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<PermissionRecord | null>(null);
  const [formData, setFormData] = useState({
    roleName: '',
    permissionScope: '',
    applicableScene: ''
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const { t } = useTranslation();
  const themePreference = useThemeStore((state) => state.theme)
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true
    if (themePreference === 'light') return false
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }, [themePreference])
  const containerClass = `permission-manage-container flex flex-col min-h-screen px-6 py-6 transition-colors ${isDark ? 'bg-slate-900 text-slate-100' : 'bg-white text-gray-900'}`
  const toolbarClass = `mb-4 p-4 rounded-lg shadow-sm flex items-center justify-between transition-colors ${isDark ? 'bg-slate-800/90' : 'bg-white'}`
  const tableWrapperClass = `flex-1 flex flex-col rounded-lg shadow transition-colors ${isDark ? 'bg-slate-800' : 'bg-white'}`
  const searchButtonClass = isDark ? 'bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white' : ''
  const secondaryButtonClass = isDark ? 'bg-gradient-to-r from-gray-500 to-gray-600 hover:from-gray-600 hover:to-gray-700 text-white' : ''

  // 核心功能：从MongoDB获取权限数据
  const fetchPermissions = useCallback(async (page = currentPage, size = pageSize, keyword = searchKeyword) => {
    console.log('===== 开始获取MongoDB权限数据 =====');
    setLoading(true);
    
    try {
      // 添加详细的请求参数日志
      const requestParams = { page, pageSize: size, roleName: keyword };
      console.log('发起API请求:', '/api/hzl/quan/list', requestParams);
      
      // 确保axios请求正确执行 - 添加时间戳避免缓存
      const response = await axios.get('/api/hzl/quan/list', {
        params: {
          ...requestParams,
          _t: Date.now() // 添加时间戳避免浏览器缓存
        },
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        }
      });
      
      console.log('API响应成功，状态码:', response.status);
      
      const responseData = response.data;
      console.log('响应数据类型:', typeof responseData);
      
      // 简化数据处理逻辑，直接处理后端返回的格式
      let permissionsData: PermissionRecord[] = [];
      let totalCount = 0;
      
      // 处理多种可能的数据格式
      if (responseData) {
        // 情况1: 标准响应格式，有success字段和data字段
        if (responseData.success && responseData.data) {
          if (responseData.data.list && Array.isArray(responseData.data.list)) {
            permissionsData = responseData.data.list;
            totalCount = responseData.data.total || permissionsData.length;
          } 
          // 情况2: data本身是数组
          else if (Array.isArray(responseData.data)) {
            permissionsData = responseData.data;
            totalCount = permissionsData.length;
          }
        }
        // 情况3: 响应直接包含list和total（可能没有success字段）
        else if (responseData.list && Array.isArray(responseData.list)) {
          permissionsData = responseData.list;
          totalCount = responseData.total || permissionsData.length;
        }
        // 情况4: 响应本身是数组
        else if (Array.isArray(responseData)) {
          permissionsData = responseData;
          totalCount = responseData.length;
        } else {
          console.warn('未识别的数据格式:', responseData);
        }
      }
      
      // 数据标准化处理
      const normalizedData = permissionsData.map((item, index) => {
        const normalizedItem: PermissionRecord = {
          id: String(item.id || item._id || index + 1),
          roleName: item.roleName || item.name || '未命名角色',
          permissionScope: item.permissionScope || item.permissions || '无权限',
          applicableScene: item.applicableScene || item.scene || '未指定',
          createTime: item.createTime || item.createdAt || new Date().toISOString(),
          ...item
        };
        return normalizedItem;
      });
      
      // 更新状态
      setPermissions(normalizedData);
      setTotal(totalCount);
      
    } catch (error) {
      console.error('获取权限数据异常:', error);
      const errorMessage = error instanceof Error ? error.message : t('common.unknownError');
      console.error('错误详情:', errorMessage);
      
      Message.error(t('permission.fetchError', { error: errorMessage }));
      setPermissions([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [t, currentPage, pageSize, searchKeyword]);

  // 初始化时获取数据
  useEffect(() => {
    console.log('Effect触发，当前页码:', currentPage, '页面大小:', pageSize, '搜索关键词:', searchKeyword);
    fetchPermissions(currentPage, pageSize, searchKeyword);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, pageSize, searchKeyword]);
  
  // 表单验证
  const validateForm = () => {
    const errors: Record<string, string> = {};
    
    if (!formData.roleName.trim()) {
      errors.roleName = t('permission.validation.roleNameRequired');
    }
    
    if (!formData.permissionScope.trim()) {
      errors.permissionScope = t('permission.validation.scopeRequired');
    }
    
    if (!formData.applicableScene.trim()) {
      errors.applicableScene = t('permission.validation.sceneRequired');
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };
  
  // 保存权限（添加或编辑）
  const handleSavePermission = async () => {
    if (!validateForm()) {
      return;
    }
    
    try {
      // 模拟API调用
      const permissionData: PermissionRecord = {
        ...formData,
        permissionScope: formData.permissionScope.split(',').map(scope => scope.trim())
      };
      
      if (currentRecord?.id) {
        // 编辑模式 - 模拟更新操作
        console.log('更新权限:', permissionData);
        Message.success(t('permission.updateSuccess'));
      } else {
        // 添加模式 - 模拟添加操作
        console.log('添加权限:', permissionData);
        Message.success(t('permission.addSuccess'));
      }
      
      // 关闭模态框并刷新数据
      setIsModalVisible(false);
    fetchPermissions(currentPage, pageSize, searchKeyword);
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : t('common.unknownError');
      Message.error(t('permission.operationFailed', { error: errorMessage }));
    }
  };
  
  // 处理表单输入变化
  const handleFormChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    
    // 清除对应字段的错误信息
    if (formErrors[name]) {
      setFormErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 辅助函数：格式化权限范围显示
  const formatPermissionScope = (scope: string | string[] | undefined | null) => {
    if (!scope) {
      return <Tag color="blue">{t('permission.none')}</Tag>;
    }
    if (Array.isArray(scope)) {
      return <Tag color="blue">{scope.join(', ')}</Tag>;
    }
    return <Tag color="blue">{String(scope)}</Tag>;
  };

  // 辅助函数：格式化时间显示
  const formatTime = (timeStr?: string | Date | null) => {
    if (!timeStr) return '--';
    try {
      const date = typeof timeStr === 'string' ? new Date(timeStr) : timeStr;
      if (isNaN(date.getTime())) return '--';
      return date.toLocaleString('zh-CN');
    } catch {
      return '--';
    }
  };

  // 事件处理函数
  const handleSearch = () => {
    setCurrentPage(1);
    // 由于fetchPermissions现在依赖searchKeyword，当搜索关键词变化时它会正确工作
    fetchPermissions(1, pageSize, searchKeyword);
  };

  const handleReset = () => {
    setSearchKeyword('');
    setCurrentPage(1);
    fetchPermissions(1, pageSize, '');
  };

  const handleRefresh = () => {
    fetchPermissions();
  };

  // 打开编辑模态框
  const handleEdit = (record: PermissionRecord) => {
    setCurrentRecord(record);
    setFormData({
      roleName: record.roleName || '',
      permissionScope: Array.isArray(record.permissionScope) 
        ? record.permissionScope.join(', ') 
        : String(record.permissionScope || ''),
      applicableScene: record.applicableScene || ''
    });
    setFormErrors({});
    setIsModalVisible(true);
  };

  // 打开添加模态框
  const handleAddPermission = () => {
    setCurrentRecord(null);
    setFormData({
      roleName: '',
      permissionScope: '',
      applicableScene: ''
    });
    setFormErrors({});
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setIsModalVisible(false);
    setCurrentRecord(null);
    setFormErrors({});
  };

  // 删除单条记录
  const handleDelete = (id: string | number) => {
    Modal.confirm({
      title: t('common.confirm'),
      content: t('permission.deleteConfirm'),
      onOk: async () => {
        try {
          // 模拟API调用
          console.log('删除权限:', id);
          Message.success(t('permission.deleteSuccess'));
          fetchPermissions(currentPage, pageSize, searchKeyword);
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : t('common.unknownError');
          Message.error(t('permission.deleteFailed', { error: errorMessage }));
        }
      }
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      Message.warning(t('permission.batchDeleteEmpty'));
      return;
    }

    Modal.confirm({
      title: t('common.confirm'),
      content: t('permission.batchDeleteConfirm', { count: selectedRowKeys.length }),
      onOk: async () => {
        try {
          // 模拟API调用
          console.log('批量删除权限:', selectedRowKeys);
          Message.success(t('permission.batchDeleteSuccess'));
          fetchPermissions(currentPage, pageSize, searchKeyword);
          setSelectedRowKeys([]);
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : t('common.unknownError');
          Message.error(t('permission.batchDeleteFailed', { error: errorMessage }));
        }
      }
    });
  };

  // 行选择
  const handleRowSelect = (id: React.Key) => {
    if (selectedRowKeys.includes(id)) {
      setSelectedRowKeys(selectedRowKeys.filter(key => key !== id));
    } else {
      setSelectedRowKeys([...selectedRowKeys, id]);
    }
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    if (selectedRowKeys.length === permissions.length) {
      setSelectedRowKeys([]);
    } else {
      setSelectedRowKeys(permissions.map(row => row.id));
    }
  };

  return (
    <div className={containerClass}>
      
      <div className="page-header mb-4">
        <h2 className="text-xl font-bold text-gray-800 dark:text-slate-100">{t('permission.title')}</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1">{t('permission.subtitle')}</p>
      </div>

      {/* 搜索和操作栏 */}
      <div className={toolbarClass}>
          <div className="flex items-center gap-2">
            <Input 
              placeholder={t('permission.searchPlaceholder')} 
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="w-[240px] border border-gray-300 dark:border-slate-600 rounded-md px-3 py-2 text-sm bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            />
            <Button size="sm" variant="default" onClick={handleSearch} className={`min-w-[96px] bg-blue-50 text-blue-600 border-blue-200 ${searchButtonClass}`}>
              {t('common.search')}
            </Button>
            <Button size="sm" variant="default" onClick={handleReset} className={`min-w-[96px] bg-gray-50 text-gray-600 border-gray-200 ${secondaryButtonClass}`}>
              {t('common.reset')}
            </Button>
            <Button size="sm" variant="default" onClick={handleRefresh} className={`min-w-[96px] bg-gray-50 text-gray-600 border-gray-200 ${secondaryButtonClass}`}>
              {t('common.refresh')}
            </Button>
          </div>
          
          <div className="flex items-center gap-2">
            <Button
              size="sm"
              variant="default"
              onClick={handleBatchDelete}
              disabled={selectedRowKeys.length === 0}
              className="min-w-[120px] bg-red-50 text-red-600 border-red-200"
            >
              {t('permission.batchDeleteWithCount', { count: selectedRowKeys.length })}
            </Button>
            <Button size="sm" variant="default" onClick={handleAddPermission} className="min-w-[120px] bg-green-50 text-green-600 border-green-200">
              {t('permission.add')}
            </Button>
          </div>
      </div>

      {/* 使用权限表格组件 */}
      <div className={tableWrapperClass}>
        <PermissionTable
          permissions={permissions}
          loading={loading}
          selectedRowKeys={selectedRowKeys}
          onRowSelect={handleRowSelect}
          onSelectAll={handleSelectAll}
          onEdit={handleEdit}
          onDelete={handleDelete}
          onAddPermission={handleAddPermission}
          formatPermissionScope={formatPermissionScope}
          formatTime={formatTime}
        />
        
        {/* 分页组件 */}
        {permissions.length > 0 && (
          <div className="flex justify-end mt-4 text-gray-700 dark:text-slate-200">
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={total}
              showSizeChanger
              showQuickJumper
              showTotal={(count) => t('permission.total', { count })}
              onChange={(page) => {
                setCurrentPage(page);
                fetchPermissions(page, pageSize, searchKeyword);
              }}
              onShowSizeChange={(page, size) => {
                setPageSize(size);
                setCurrentPage(page);
                fetchPermissions(page, size, searchKeyword);
              }}
            />
          </div>
        )}
      </div>
      
      {/* 权限编辑/添加模态框 */}
      <Modal
        title={currentRecord ? t('permission.edit') : t('permission.add')}
        visible={isModalVisible}
        onCancel={handleCloseModal}
        footer={[
          <Button key="cancel" size="sm" variant="outline" onClick={handleCloseModal} className="min-w-[96px]">{t('common.cancel')}</Button>,
          <Button key="save" size="sm" variant="primary" onClick={handleSavePermission} className="min-w-[96px]">{t('common.save')}</Button>
        ]}
      >
        <div className="space-y-4">
          <div>
            <Input
              label={t('role.name')}
              name="roleName"
              value={formData.roleName}
              onChange={handleFormChange}
              placeholder={t('role.namePlaceholder')}
              error={formErrors.roleName}
            />
          </div>
          
          <div>
            <Input
              label={t('permission.table.scope')}
              name="permissionScope"
              value={formData.permissionScope}
              onChange={handleFormChange}
              placeholder={t('permission.scopePlaceholder')}
              error={formErrors.permissionScope}
            />
          </div>
          
          <div>
            <Input
              label={t('permission.table.scene')}
              name="applicableScene"
              value={formData.applicableScene}
              onChange={handleFormChange}
              placeholder={t('permission.scenePlaceholder')}
              error={formErrors.applicableScene}
            />
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default PermissionManage
